import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};

    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        int m = image.length;
        int n = image[0].length;


        Queue<int[]> queue = new LinkedList<>();

        int startColor = image[sr][sc];

        if (startColor == color) {
            return image;
        }

        queue.offer(new int[]{sr, sc});

        while (!queue.isEmpty()) {
            int[] temp = queue.poll();
            int x = temp[0];
            int y = temp[1];
            image[x][y] = color;
            for (int i = 0; i < 4; i++) {
                int xx = x + dx[i];
                int yy = y + dy[i];
                if (xx >= 0 && yy >= 0 && xx < m && yy < n && image[xx][yy] == startColor) {
                    queue.offer(new int[]{xx, yy});
                }
            }
        }

        return image;
    }

}
